import { makeAutoObservable } from 'mobx';
import { clearToken, getToken, http, setToken } from '@/utils';

class LoginStore {
  token = getToken() || '';
  userName = '';

  constructor() {
    // 给对象添加响应式
    // 原理就是递归给数据添加getter 和setter，通过数据拦截监听数据的变化
    makeAutoObservable(this);
  }

  // 登录 记录token
  loginIn = async ({ username, password }) => {
    const res = await http.post(`login`, {
      body: { username, password }
    });
    this.token = res.user.token;
    setToken(this.token);
    return { username };
  };

  // 登出
  loginOut = () => {
    this.token = '';
    this.userName = '';
    clearToken();
  };

  // token检查
  checkToken = async () => {
    try {
      const res = await http.post(`tokenCheck`);
      if (res.code === 10000) {
        this.userName = res.username;
        return { isValid: true, username: res.username };
      } else {
        return { isValid: false, username: '游客' };
      }
    } catch (e) {
      console.log(e);
    }
  };
}

export default LoginStore;
